package svc

import (
	"context"
	"gozerogateway/api/internal/svc"
	"gozerogateway/api/internal/types"
	"gozerogateway/common/errorx"
	"regexp"
	"strings"

	"github.com/zeromicro/go-zero/core/logx"
)

type ServiceAddHttpLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewServiceAddHttpLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ServiceAddHttpLogic {
	return &ServiceAddHttpLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *ServiceAddHttpLogic) ServiceAddHttp(req *types.ServiceAddHttpReq) error {
	// todo: add your logic here and delete this line

	//if  len(strings.TrimSpace(req.ServiceName)) <6 || len(strings.TrimSpace(req.ServiceName)) >128{
	//	reqStr, _ := json.Marshal(req) //func Marshal(v any) ([]byte, error)
	//	logx.WithContext(l.ctx).Errorf("servicename input num error,参数:%s", reqStr)
	//	return errorx.NewDefaultError("servicename num error")
	//}

	matched, _ := regexp.Match(`^[a-zA-Z0-9_]{6,128}$`, []byte(req.ServiceName)) //byte
	if matched != true {
		return errorx.NewDefaultError("servicename input num or character error")
	}

	matched2, _ := regexp.Match(`^\S+$`, []byte(req.Rule)) //byte
	if matched2 != true {
		return errorx.NewDefaultError("rule must be not null")
	}

	//matched3, _ := regexp.Match(`\S+`, []byte(req.UrlRewrite)) //byte
	//if matched3 != true {
	//	return errorx.NewDefaultError("urlrewrite must be not null")
	//}
	//
	//matched4, _ := regexp.Match(`\S+`, []byte(req.HeaderTransfor)) //byte
	//if matched4 != true {
	//	return errorx.NewDefaultError("headertransfor must be not null")
	//}

	//empty character = empty
	if req.UrlRewrite == "" {
		return errorx.NewDefaultError("urlrewrite empty")
	}
	for _, ms := range strings.Split(req.UrlRewrite, "\n") {
		if len(strings.Split(ms, " ")) != 2 {
			return errorx.NewDefaultError("urlrewrite input error")
		}
	}
	if req.HeaderTransfor == "" {
		return errorx.NewDefaultError("headertransfor empty")
	}
	//add headername headervalue
	for _, ms2 := range strings.Split(req.HeaderTransfor, "\n") {
		if len(strings.Split(ms2, " ")) != 3 {
			return errorx.NewDefaultError("headertransfor input error")
		}
	}

	//if req.IpList==""{
	//	return errorx.NewDefaultError("iplist empty")
	//}
	for _, ms3 := range strings.Split(req.IpList, "\n") {
		if matched3, _ := regexp.Match(`^\S+\:\d+$`, []byte(ms3)); !matched3 {
			return errorx.NewDefaultError("iplist input error")
		}
	}

	for _, ms4 := range strings.Split(req.WeightList, "\n") {
		if matched4, _ := regexp.Match(`^\d+$`, []byte(ms4)); !matched4 {
			return errorx.NewDefaultError("weightlist input error")
		}
	}

	if len(strings.Split(req.IpList, "\n")) != len(strings.Split(req.WeightList, "\n")) {
		return errorx.NewDefaultError("iplist num != weightlist num")
	}

	return nil
}
